package com.csweimei.rentmanagementtreasure.viewModel;

import android.app.Application;
import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.NonNull;

import com.csweimei.rentmanagementtreasure.MainActivity;
import com.csweimei.rentmanagementtreasure.MyApplication;
import com.csweimei.rentmanagementtreasure.R;
import com.csweimei.rentmanagementtreasure.SplashActivity;
import com.csweimei.rentmanagementtreasure.http.Repository;
import com.csweimei.rentmanagementtreasure.utils.UserUtils;
import com.gtdev5.geetolsdk.mylibrary.beans.ResultBean;
import com.gtdev5.geetolsdk.mylibrary.beans.UpdateBean;
import com.gtdev5.geetolsdk.mylibrary.callback.BaseCallback;
import com.gtdev5.geetolsdk.mylibrary.contants.Contants;
import com.gtdev5.geetolsdk.mylibrary.http.Base64HttpUtils;
import com.gtdev5.geetolsdk.mylibrary.util.DataSaveUtils;
import com.gtdev5.geetolsdk.mylibrary.util.DeviceUtils;
import com.gtdev5.geetolsdk.mylibrary.util.SpUtils;
import com.gtdev5.geetolsdk.mylibrary.util.ToastUtils;
import com.gtdev5.geetolsdk.mylibrary.util.Utils;
import com.gtdev5.geetolsdk.mylibrary.widget.CenterDialog;

import java.util.Timer;
import java.util.TimerTask;

import me.goldze.mvvmhabit.base.BaseViewModel;
import okhttp3.Request;
import okhttp3.Response;

public class SplashVM extends BaseViewModel<Repository> {
    private boolean isFirstRegister; // 是否首次注册

    public SplashVM(@NonNull Application application, Repository model) {
        super(application, model);
    }

    SplashActivity mSplashActivity;
    public void setContext(SplashActivity splashActivity) {
        this.mSplashActivity = splashActivity;
    }

    /***
     * 绑定device数据
     */
    public void bindDevice() {
        isFirstRegister = SpUtils.getInstance().getBoolean(Contants.FIRST_REGISTER, true);

        if (TextUtils.isEmpty(DeviceUtils.getSpDeviceId()) && TextUtils.isEmpty(DeviceUtils.readDeviceID(mSplashActivity))) {
            // app和sd卡都没有，都存一份
            String imei = DeviceUtils.getUUID();
            DeviceUtils.saveDeviceID(imei, mSplashActivity);
            DeviceUtils.putSpDeviceId(imei);
        } else if (TextUtils.isEmpty(DeviceUtils.getSpDeviceId()) && !TextUtils.isEmpty(DeviceUtils.readDeviceID(mSplashActivity))) {
            // sd卡有，app没有，则存一份到app
            DeviceUtils.putSpDeviceId(DeviceUtils.readDeviceID(mSplashActivity));
        } else {
            // app有，sd卡没有，则存一份到sd卡
            DeviceUtils.saveDeviceID(DeviceUtils.getSpDeviceId(), mSplashActivity);
        }
//        DeviceUtils.putSpDeviceId("");
        registerId();
    }

    /**
     * 注册设备id
     */
    private void registerId() {
        if (isFirstRegister) {
            if (Utils.isNetworkAvailable(mSplashActivity)) {
                Base64HttpUtils.getInstance().postRegister(new BaseCallback<ResultBean>() {
                    @Override
                    public void onRequestBefore() {
                    }
                    @Override
                    public void onFailure(Request request, Exception e) {
                        showRestartDialog();
                    }

                    @Override
                    public void onSuccess(Response response, ResultBean o) {
                        if (o != null) {
                            if (o.isIssucc()) {
                                // 注册成功，调取App数据接口
                                SpUtils.getInstance().putBoolean(Contants.FIRST_REGISTER, false);
                                if (model.isLogin()){
                                    getUpdateInfo();
                                }else {
                                    jumpToNext();
                                }
                            } else {
                                // 注册失败，弹出提示
                                if (!TextUtils.isEmpty(o.getMsg())) {
                                    ToastUtils.showShortToast(o.getMsg());
                                }
                            }
                        }
                    }

                    @Override
                    public void onError(Response response, int errorCode, Exception e) {
                        showRestartDialog();
                    }
                });
            } else {
                showRestartDialog();
            }
        } else {
            if (model.isLogin()){
                getUpdateInfo();
            }else {
                jumpToNext();
            }
        }
    }

    /**
     * 获取App数据信息
     */
    private void getUpdateInfo() {
        UpdateBean updateBean = DataSaveUtils.getInstance().getUpdate();
        if (Utils.isNetworkAvailable(mSplashActivity)) {
            Base64HttpUtils.getInstance().postUpdate(new BaseCallback<UpdateBean>() {
                @Override
                public void onRequestBefore() {
                }

                @Override
                public void onFailure(Request request, Exception e) {
                    if (updateBean != null) {
                        jumpToNext();
                        return;
                    }
                    showRestartDialog();
                }

                @Override
                public void onSuccess(Response response, UpdateBean o) {
                    if (o != null && o.getIssucc()) {
                        // 数据获取成功跳转到下个页面
                        jumpToNext();
                        UserUtils.setVip(o.getVip());
                    } else {
                        // 更新失败，弹出提示
                        if (!TextUtils.isEmpty(o.getMsg())) {
                            ToastUtils.showShortToast(o.getMsg());
                        }
                    }
                }

                @Override
                public void onError(Response response, int errorCode, Exception e) {
                    if (updateBean != null) {
                        jumpToNext();
                        return;
                    }
                    showRestartDialog();
                }
            });
        } else {
            if (updateBean != null) {
                jumpToNext();
                return;
            }
            showRestartDialog();
        }
//        checkLogin();
    }

    private void jumpToNext() {
        MyApplication.getInstance().initUmeng(mSplashActivity);
        final Timer timer=new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                startActivity(MainActivity.class);
                timer.cancel();
                mSplashActivity.finish();
            }
        },1500);
    }

    /**
     * 校验登陆
     */
    private void checkLogin() {
        if (Utils.isNetworkAvailable(mSplashActivity)) {
            if (!TextUtils.isEmpty(Utils.getUserId())) {
                // 登录过
                Base64HttpUtils.getInstance().checkLogin(new BaseCallback<ResultBean>() {
                    @Override
                    public void onRequestBefore() {}

                    @Override
                    public void onFailure(Request request, Exception e) {}

                    @Override
                    public void onSuccess(Response response, ResultBean o) {
                        if (o != null) {
                            if (o.isIssucc()) {
                                Log.e("校验登录:", "已经登录过");
                            } else {
                                if (!TextUtils.isEmpty(o.getMsg())) {
                                    ToastUtils.showShortToast(o.getMsg());
                                }
                                Log.e("校验登录:", "已在别机登录，本机下线");
                            }
                        }
                    }

                    @Override
                    public void onError(Response response, int errorCode, Exception e) {}
                });
            }
        }
    }

    /**
     * 提示网络问题重启应用弹框
     */
    public void showRestartDialog() {
        int[] ids = new int[]{R.id.dialog_bt_ok};
        CenterDialog dialog = new CenterDialog(mSplashActivity, R.layout.gt_dialog_restart_app, ids, false);
        dialog.setOnCenterClickListener((dial, view) -> {
            if (view.getId() == R.id.dialog_bt_ok) {
                if (!mSplashActivity.isFinishing()) {
                    dialog.dismiss();
                }
                finish();
            }
        });
        if (!mSplashActivity.isFinishing()) {
            dialog.show();
            dialog.setCanceledOnTouchOutside(false);
            dialog.setCancelable(false);
        }
    }
}
